const express=require("express");
const handleDB=require("../db/handleDB");
const common=require("../utils/common");
const constant=require("../utils/constant");
const md5=require("md5");
const Captcha=require("../utils/captcha");
const keys = require("../utils/keys");
const jwt=require("jsonwebtoken");
require("../utils/filter");

const router=express.Router();

router.get("/passport/image_code/:float",(req,res)=>{

    let captchaObj=new Captcha();
    let captcha=captchaObj.getCode();

    req.session['ImageCode']=captcha.text;
    console.log(req.session);
    
    res.setHeader('Content-Type','image/svg+xml');
    res.send(captcha.data);

})

router.post("/passport/register",(req,res)=>{

    (async function(){
        let {username,image_code,password,agree}=req.body
        if(!username || !image_code || !password || !agree){
            res.send({errmsg:"缺少必传参数"})
            return
        }

        if(image_code.toLowerCase() !== req.session["ImageCode"].toLowerCase()){
            res.send({errmsg:"验证码填写错误"})
            return
        }

        let result= await handleDB(res,"user","find","数据库查询出错",`user_name="${username}"`)
        console.log("result为：",result);

        if(result[0]){
            res.send({errmsg:"用户名已经被注册"})
            return
        }

        let result2=await handleDB(res,"user","insert","数据库插入数据出错",{
            user_name:username,
            password:md5(md5(password)+keys.password_salt),
            nick_name:username,
            last_login:new Date().toLocaleString('chinese',{hour12:false})
        })

        req.session["user_id"]=result2.insertId

        res.send({errno:'0',errmsg:"注册成功"})


    })();

})

router.post("/passport/login",(req,res)=>{
    (async function(){
        let {username,password}=req.body
        if(!username || !password){
            res.send({errmsg:"缺少必传参数"})
            return
        }

        let result= await handleDB(res,"user","find","数据库查询出错",`user_name="${username}"`)

        if(!result[0]){
            res.send({errmsg:"用户名未注册，登录失败"})
            return
        }

        if(md5(md5(password)+keys.password_salt)!==result[0].password){
            res.send({errmsg:"用户名或者密码不正确，登录失败"})
            return
        }

        req.session["user_id"]=result[0].user_id
        console.log(result[0].user_id)

        await handleDB(res,"user","update","数据库修改出错",`user_id=${result[0].user_id}`,{last_login:new Date().toLocaleString('chinese',{hour12:false})})

        res.send({errno:'0',errmsg:"登录成功"})

    })();
})

router.post("/passport/logout",(req,res)=>{
    delete req.session["user_id"]
    res.send({errmsg:"退出登录成功"})
})



module.exports=router